<template>
  <!-- 合并头部 -->
  <div class="container">
    <header class="main-header">
      <h3 class="app-title" style="text-align: center">首页</h3>
      <div class="user-info">
        <span class="username">👤 {{ userInfo }}</span>
      </div>
    </header>

    <!-- 自动播放通知栏 -->
    <div class="notification-bar">
      <div>
        <el-button @click="handleSwitch(-1)">
          <el-icon><ArrowLeftBold /></el-icon>
        </el-button>
      </div>

        <transition
            :name="(direction > 0) ? 'slide-right' : 'slide-left'"
            mode="out-in"
        >
          <div
              v-if="notifications.length > 0"
              :key="currentIndex"
              class="notification-item"
              style="font-weight: bold"
          >
            {{ notifications[realIndex] }}
          </div>
          <div v-else class="empty-notice">暂无通知</div>
        </transition>

      <div style="right: 0">
        <el-button @click="handleSwitch(1)">
          <el-icon><ArrowRightBold /></el-icon>
        </el-button>
      </div>

    </div>

    <!-- 快速操作区 -->
    <section class="quick-action">
      <el-button class="btn-primary" @click="navigateToCreate">
        <el-icon style="color: #bf1515"><Flag /></el-icon>
        🚗 立即拼车
      </el-button>
      <span style="margin-left: 15px; font-weight: bold;">🚗      🚗      🚗go go go 出 发 咯 ！ !      🚗      🚗      🚗</span>
    </section>

    <!-- 行程概览 -->
    <section class="trip-section">
      <div class="section-title">
        <span>我的行程</span>
      </div>
      <div class="trip-list">
        <template v-if="loading">
          <div class="skeleton-card"></div>
          <div class="skeleton-card"></div>
        </template>
        <template v-else>
          <div v-if="loading" class="loading-container">
            <el-icon class="loading-icon"><Loading /></el-icon>
            <span>正在拼命加载中...</span>
          </div>
          <div v-if="trips.length === 0" class="empty-tip">
            📍 暂无进行中的行程
          </div>
          <article
              v-for="trip in trips"
              :key="trip.id"
              class="trip-card"
              @click="showTripDetail(trip.id)"
          >
            <div class="trip-content">
              <div class="route-info">
                <span class="from">{{ trip.from }}</span>
                <span class="arrow">→</span>
                <span class="to">{{ trip.to }}</span>
              </div>
              <time class="departure-time">{{ formatTime(trip.time) }}</time>
            </div>
            <div class="status-indicator" :class="trip.status">
              {{ getStatusText(trip.status) }}
            </div>
          </article>
        </template>
      </div>
    </section>


  </div>
</template>

<script setup>
import { ref, onMounted, computed,reactive } from 'vue'
import { useRouter } from 'vue-router'
import {ArrowLeftBold, ArrowRightBold, Flag} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";

//router跳转页面
const router = useRouter()
//用户名数据
const userInfo = ref('加载中...')
try {
  const userData = JSON.parse(localStorage.getItem('car-home-user'))
  userInfo.value = userData?.userName || '未登录用户'
} catch (error) {
  console.error('用户信息解析失败:', error)
  userInfo.value = '数据异常'
}

// 数据初始化
const loading = ref(true)
const trips = ref([])
const recommendedRoutes = ref([])

const currentIndex = ref(0);
const direction = ref(1) // 1: 向右，-1: 向左
const autoTimer = ref(null)
const notifications = ref([
  '当一束光照进铁塔，铁塔里的肮脏龌龊被显现，这束光便有了罪 ---- 尼采',
  '我要做远方忠诚的儿子，和物质的短暂情人 ---- 海子',
  '君埋泉下泥销骨，我寄人间雪满头 ---- 白居易《梦微之》',
  '秋是第二春。此时，每一片叶子都是一朵鲜花 ---- 加缪《秋是第二个春天》',
  '我是廊外的一株花树。花来。花去。而树犹在 ---- 余光中《听听那冷雨》',
  '橘子不是唯一的水果，你的人生还有别的可能 ---- 【英】珍妮特·温特森《橘子不是唯一的水果》',
  '表达自己的软弱，即是表达对他人的需要 ---- 史铁生《务虚笔记》',
  '1',
  '2',
  '3',
])
//当前页码
const realIndex = computed(() => currentIndex.value % notifications.value.length)

//左右移notifications
const handleSwitch = (step) => {
  direction.value = step
  currentIndex.value = (currentIndex.value + step + notifications.value.length)
      % notifications.value.length

  // 重置自动播放定时
  resetAutoPlay()
}
//自动播放
const startAutoPlay = () => {
  autoTimer.value = setInterval(() => {
    direction.value = 1
    currentIndex.value = (currentIndex.value + 1) % notifications.value.length
  }, 6000)//6s一次
}
//重置自动播放
const resetAutoPlay = () => {
  clearInterval(autoTimer.value)
  startAutoPlay()
}
//自动播放的启动函数
onMounted(() => {
  if (notifications.value.length > 0) {
    startAutoPlay()
  }
})

const information = reactive({
  orderId:'',
  departure:'',
  destination:'',
  departureTime:'',
  status:'',
  list:{},
})

const selectinfor = async () => {
  try {
    const userdata = JSON.parse(localStorage.getItem('car-home-user'))
    console.log('当前用户ID:', userdata?.userId) // 添加用户ID日志

    const res = await request.get('/Home/CarInformation/hhh', {
      params: { userId: userdata?.userId }
    })

    console.log('接口响应数据:', res) // 添加响应日志

    if (res.code === '200') {
      information.list = res.data
      console.log('接收到的数据:', information.list) // 添加数据日志
    } else {
      ElMessage.error(`请求失败: ${res.msg}`)
    }
  } catch (error) {
    console.error('请求异常:', error)
    ElMessage.error(`请求异常: ${error.message}`)
  }
}

//我的拼车（待完成）
const fetchData = async () => {
  try {
    loading.value = true
    await selectinfor()

    // 空数据检查
    if (!information.list) {
      throw new Error('未获取到有效数据')
    }

    // 统一转换为数组
    const dataList = Array.isArray(information.list)
        ? information.list
        : [information.list]

    // 字段缺失检查
    trips.value = dataList.map(item => {
      if (!item?.orderId || !item?.departure) {
        console.error('无效数据项:', item)
        return null
      }
      return {
        id: item.orderId,
        from: item.departure,
        to: item.destination || '未设置目的地',
        time: item.departureTime || '未知时间',
        status: item.status === 0 ? 'processing' : 'completed'
      }
    }).filter(Boolean) // 过滤无效项
  } catch (error) {
    ElMessage.error(`数据加载失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

const getStatusText = (status) => {
  const statusMap = {
    processing: '进行中',
    booked: '已预约'
  }
  return statusMap[status] || '未知状态'
}

onMounted(fetchData)

// 方法定义
const navigateToCreate = () => {
  router.push('/Home/runCar')
}

const showTripDetail = (tripId) => {
  router.push(`/trip/${tripId}`)
}

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleString()
}

</script>

<style scoped>
:root {
  --primary-color: #709ae8;
  --secondary-color: #b08ddf;
  --success-color: #28a745;
  --warning-color: #ffc107;
  --text-light: #ffffff;
  --shadow-normal: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 15px;
}

.box {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.trip-section {
  background-color: white;
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-title {
  text-align: center;
  align-items: center;
  font-size: 24px;
  font-weight: bold;
  height: 50px;
  border-bottom: 2px solid #0742b1;
}

.main-header {
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.notification-bar {
  background-color: white;
  max-width: 1200px;
  margin: 20px auto;
  padding: 10px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: 40px;
  overflow: hidden;
  display: flex;
  align-items: center;
}

.notification-item {
  width: 100%;
  text-align: center;
  white-space: nowrap;
}

.status-indicator {
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
  color: white;

  &.processing {
    background-color: #409eff;
  }
  &.booked {
    background-color: #e6a23c;
  }
  &.completed {
    background-color: #67c23a;
  }
}

.departure-time {
  color: #666;
  font-size: 0.9em;
}

.slide-right-enter-active,
.slide-right-leave-active,
.slide-left-enter-active,
.slide-left-leave-active {
  transition: all 0.8s ease;
  width: 100%;
}

.slide-right-enter-from {
  transform: translateX(100%);
  opacity: 0;
}

.slide-right-leave-to {
  transform: translateX(-100%);
  opacity: 0;
}

.slide-left-enter-from {
  transform: translateX(-100%);
  opacity: 0;
}

.slide-left-leave-to {
  transform: translateX(100%);
  opacity: 0;
}

.empty-notice {
  color: #999;
  font-style: italic;
}

@keyframes scroll {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(-100%);
  }
}

.trip-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: var(--text-light);
  border-radius: 8px;
  margin: 10px 0;
  box-shadow: var(--shadow-normal);
  transition: transform 0.2s;
}

.trip-card:hover {
  transform: translateY(-2px);
}

.route-grid {
  display: grid;
  gap: 15px;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}
</style>